#include "chatdialog.h"
#include "ui_chatdialog.h"
#include "chatlistitem.h"
#include "addcontactitem.h"
#include "messageListItem/messagefriendlistitem.h"
#include "messageListItem/messageuserlistitem.h"
#include "messageListItem/messagetimelistitem.h"
#include "utils.h"
#include <QRandomGenerator>
#include <searchlineedit.h>
#include <QScrollBar>
#include <QScroller>
#include <QScrollerProperties>
#include <QEasingCurve>
#include <httpmgr.h>
#include <QTextFrame>
#include <QTextBlock>
#include <QPainter>
#include <QMessageBox>

ChatDialog::ChatDialog(int id,QString name,QString email,
                       QString identity, QString avatar) :
    QDialog(),
    ui(new Ui::ChatDialog),
    user_id(id),
    user_name(name),
    user_email(email),
    user_identity(identity),
    user_avatar(avatar)
{
    ui->setupUi(this);
    init_ui();

    timer = new QTimer();
    // 设置时间间隔为两分钟（120000 毫秒）
    timer->setInterval(120000);
    // 连接定时器的 timeout 信号到匿名函数
    connect(timer, &QTimer::timeout, [&]() {
        isNewGroupMsg = true;//超过两分钟没发送消息，下次消息为新一组
        timer->stop();
    });

}

ChatDialog::~ChatDialog()
{
    delete ui;
}

void ChatDialog::loadImage(QLabel* label,const QByteArray &pictureByteArray)
{
    QPixmap pixmap;
    if (pixmap.loadFromData(pictureByteArray))
    {
        label->setPixmap(pixmap.scaled(label->size(),
                                             Qt::KeepAspectRatio, Qt::SmoothTransformation));
    }
    else
    {
        qDebug() << "loadAvatar函数加载图片数据失败！";
    }
}





void ChatDialog::mousePressEvent(QMouseEvent *event)
{
    Q_UNUSED(event);
    ui->lineEdit_chat->clearFocus();
    //如果_add_or_create_dlg界面存在，销毁之
    if(_add_or_create_dlg != nullptr)
    {
        // 先尝试断开可能存在的连接
        disconnect(_add_or_create_dlg, &AddOrCreateContactDialog::add_contact_sig,
                   this, &ChatDialog::createAddContactForm);
        _add_or_create_dlg->deleteLater();
        _add_or_create_dlg = nullptr;
    }
    if(_switchkey_dlg != nullptr)
    {
        disconnect(_switchkey_dlg,&SwitchKeyDialog::openKey_sig,this,&ChatDialog::keyEnterIsTrue);
        disconnect(_switchkey_dlg,&SwitchKeyDialog::forbidKey_sig,this,&ChatDialog::keyEnterIsFalse);
        _switchkey_dlg->deleteLater();
        _switchkey_dlg = nullptr;
        ui->switch_key_rabtn->setChecked(false);
    }
}









void ChatDialog::showUndoBtn()
{
    ui->undo_btn->setVisible(true);
}

void ChatDialog::hideUndoBtn()
{
    if( (ui->undo_btn->isVisible()) && (ui->lineEdit_chat->text().isEmpty()) )
        ui->undo_btn->setVisible(false);
}

void ChatDialog::showScrollBar()
{
    ui->chat_list->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
}

void ChatDialog::hideScrollBar()
{
    ui->chat_list->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
}

void ChatDialog::createAddContactForm()
{

    _add_contact_dlg = new AddContactForm(this);
    _add_contact_dlg->setWindowFlag(Qt::Window);
    connect(_add_contact_dlg,&AddContactForm::destroyed,this,
            &ChatDialog::toTheEmptyContactForm);
    _add_contact_dlg->show();

    //删除添加好友/群聊或创建群聊按钮显示界面，防止多次创建造成程序奔溃
    disconnect(_add_or_create_dlg, &AddOrCreateContactDialog::add_contact_sig,
               this, &ChatDialog::createAddContactForm);
    _add_or_create_dlg->deleteLater();
    _add_or_create_dlg = nullptr;
}

void ChatDialog::toTheEmptyContactForm()
{
    disconnect(_add_contact_dlg,&AddContactForm::destroyed,this,
               &ChatDialog::toTheEmptyContactForm);
    _add_contact_dlg = nullptr;

}

void ChatDialog::keyEnterIsTrue()
{
    ui->input_textEdit->switch_key_Enter = true;
    connect(_switchkey_dlg,&SwitchKeyDialog::openKey_sig,this,&ChatDialog::keyEnterIsTrue);
    connect(_switchkey_dlg,&SwitchKeyDialog::forbidKey_sig,this,&ChatDialog::keyEnterIsFalse);
    _switchkey_dlg->deleteLater();
    _switchkey_dlg = nullptr;
}

void ChatDialog::keyEnterIsFalse()
{
    ui->input_textEdit->switch_key_Enter = false;
    disconnect(_switchkey_dlg,&SwitchKeyDialog::openKey_sig,this,&ChatDialog::keyEnterIsTrue);
    disconnect(_switchkey_dlg,&SwitchKeyDialog::forbidKey_sig,this,&ChatDialog::keyEnterIsFalse);
    _switchkey_dlg->deleteLater();
    _switchkey_dlg = nullptr;
}




void ChatDialog::on_undo_btn_clicked()
{
    ui->lineEdit_chat->clear();
    ui->lineEdit_chat->clearFocus();
    ui->undo_btn->setVisible(false);
}




void ChatDialog::on_add_or_create_contact_clicked()
{
    //删除添加联系人界面，防止多次创建联系人界面造成程序奔溃
    if(_add_contact_dlg != nullptr){
        _add_contact_dlg->deleteLater();
        //_add_contact_dlg = nullptr;
    }


    if(_add_or_create_dlg != nullptr)
    {
        // 先尝试断开可能存在的连接
        disconnect(_add_or_create_dlg, &AddOrCreateContactDialog::add_contact_sig,
                   this, &ChatDialog::createAddContactForm);
        _add_or_create_dlg->deleteLater();
        _add_or_create_dlg = nullptr;
        return;
    }
    _add_or_create_dlg = new AddOrCreateContactDialog(this);
    _add_or_create_dlg->setGeometry(ui->add_or_create_contact->pos().x() + 70,
                                    ui->add_or_create_contact->pos().y() + 25, 120, 60);
    connect(_add_or_create_dlg, &AddOrCreateContactDialog::add_contact_sig,
            this, &ChatDialog::createAddContactForm);
    _add_or_create_dlg->show();
}

/*发送消息，首先判断是否是新组消息，是则显示时间，
 * 之后判断是否为图片消息，图片需要发送两次消息，即图片数据与图片文本路径，用户根据路径从服务器存取图片
 * 最后是正常的文本消息发送与显示
 */
void ChatDialog::on_send_mes_btn_clicked()
{
    //获取选中qlistwidgetitem数据
    QListWidgetItem *item_cur = ui->chat_list->currentItem();
    ChatListItem *customItem = qobject_cast<ChatListItem*>(ui->chat_list->itemWidget(item_cur));
    /*
     * QStringList储存顺序为<<user_id<<user_msg<<user_name<<user_email<<user_avatar
    */
    QStringList strlist = customItem->GetInfo();
    // 创建 JSON消息对象
    //    UserId     int64  //发送者
    //    TargetId   int64  //接受者
    //    Type       int    //发送类型  1私聊  2群聊  3心跳 4时间
    //    Media      int    //消息类型  1文字 2表情包 3语音 4图片 /表情包
    //    Content    string //消息内容
    //    CreateTime uint64 //创建时间
    //    ReadTime   uint64 //读取时间
    QJsonObject jsonObject;
    jsonObject["UserId"] = user_id;
    jsonObject["TargetId"] = strlist[0].toInt();
    jsonObject["CreateTime"] = 0;//当消息到达服务器时按照服务器时间赋值

    //判断离上次发送消息是否超过两分钟，超过则为新组消息
    if(isNewGroupMsg){
        qDebug()<<1;
        QDateTime currentDateTime = QDateTime::currentDateTime();
        qint64 timesNow = currentDateTime.toSecsSinceEpoch();//获取当前时间戳
        // 获取时间部分
        QTime currentTime = currentDateTime.time();
        // 格式化时间，只保留小时和分钟
        QString timeStr = QString::number(QDateTime::currentSecsSinceEpoch());
        auto *messageitem = new messageTimeListItem;
        messageitem->setTime(timeStr);
        auto *item = new QListWidgetItem;
        item->setSizeHint(QSize(0,40));
        ui->chat_messages_list->addItem(item);
        ui->chat_messages_list->setItemWidget(item,messageitem);
        isNewGroupMsg = false;
        timer->start();//开始记时间，超过两分钟则为新组
        // 将 JSON 对象转换为 JSON 文档
        jsonObject["Type"] = 4;
        jsonObject["Media"] = 1;
        jsonObject["Content"] = QString::number(timesNow);
        QJsonDocument jsonDoc(jsonObject);
        // 将 JSON 文档转换为字符串发送
        QString jsonString = jsonDoc.toJson(QJsonDocument::Compact);
        emit sendTextMsg(jsonString);//发送时间消息

    }

    //获取input_textEdit中的数据，判断是否为图片数据，如果是，则发送图片数据与图片文本消息，否则只发送文本消息
    QTextDocument *document = ui->input_textEdit->document();
    for (QTextBlock block = document->begin(); block.isValid(); block = block.next()) {
        for (QTextBlock::iterator it = block.begin();!it.atEnd(); ++it) {
            QTextFragment fragment = it.fragment();
            if (fragment.charFormat().isImageFormat()) {
                QTextImageFormat imageFormat = fragment.charFormat().toImageFormat();
                QString imageName = imageFormat.name();
                QVariant resource = document->resource(QTextDocument::ImageResource, QUrl(imageName));
                if (resource.type() == QVariant::Image) {
                    QImage image = resource.value<QImage>();
                    QPixmap msgPix = QPixmap::fromImage(image);
                    //在消息窗口显示该图片消息
                    auto *messageitem = new messageUserListItem;
                    QPixmap pixmap = ui->avatar->pixmap();//复制左侧用户头像
                    messageitem->setInfo(msgPix,imageName,pixmap);
                    auto *item = new QListWidgetItem;
                    item->setSizeHint(msgPix.size() + QSize(0,30));
                    ui->chat_messages_list->addItem(item);
                    ui->chat_messages_list->setItemWidget(item,messageitem);
                    ui->input_textEdit->clear();

                    // 新文件名,两个用户之间的聊天标识符+创建文件时的时间戳，
                    //保证每个用户聊天之间的文件名的唯一性
                    QString newName = strlist[1] + "-" + imageName;
                    //更新聊天窗口item的消息与时间
                    customItem->setMsgAndTime(newName,QDateTime::currentSecsSinceEpoch());
                    // 创建QFile对象
                    QString fileOldName = QDir::currentPath() + "//" + IMAGE_MSG_PATH + imageName;
                    QString fileNewName = QDir::currentPath() + "//" + IMAGE_MSG_PATH + newName;
                    QFile file(fileOldName);
                    // 使用rename()函数重命名文件
                    if (file.rename(fileNewName)) {
                        qDebug() << "文件重命名成功！";
                    } else {
                        qDebug() << "文件重命名失败：" << file.errorString();
                    }
                    //发送图片消息到服务器
                    QByteArray imageData = readBytesFile(IMAGE_MSG_PATH,newName);
                    // 将文件名转换为 QByteArray
                    QByteArray nameArray = newName.toUtf8();
                    // 准备分隔符
                    QByteArray delimiter = "\n";
                    // 拼接数据
                    QByteArray finalData = nameArray + delimiter + imageData;
                    emit sendImageMsg(finalData);//发送二进制图片资源
                    jsonObject["Content"] = newName;//文件名作为文本消息，用户读取到后在通过文件名请求图片资源
                    jsonObject["Media"] = 4;//消息类型  1文字 2表情包 3语音 4图片 /表情包
                    jsonObject["Type"] = 1;
                    // 将 JSON 对象转换为 JSON 文档
                    QJsonDocument jsonDoc(jsonObject);
                    // 将 JSON 文档转换为字符串发送
                    QString jsonString = jsonDoc.toJson(QJsonDocument::Compact);
                    emit sendTextMsg(jsonString);//发送文件名的文本消息
                    return;
                }
            }
        }
    }

    //只发送文本消息
    QString chatText = ui->input_textEdit->toPlainText();
    int height = fontheight(chatText);
//    if( chatText.isEmpty() )
//        return;
//    QFont font;
//    // 获取默认字体下文本的度量信息
//    QFontMetrics metrics(font);
//    int textHeight = metrics.height();//单个字体高度
//    int count = chatText.count("\n");// \n换行符数量
//    int height = count * textHeight + count * 1 + 60;//实际设置item高度，文本内容宽度qlabel会自适应缩放

    auto *messageitem = new messageUserListItem;
    QPixmap pixmap = ui->avatar->pixmap();//复制左侧用户头像
    messageitem->setInfo(chatText,pixmap);
    auto *item = new QListWidgetItem;
    item->setSizeHint(QSize(0,height));
    ui->chat_messages_list->addItem(item);
    ui->chat_messages_list->setItemWidget(item,messageitem);
    ui->input_textEdit->clear();
    //更新聊天窗口item的消息与时间
    customItem->setMsgAndTime(chatText,QDateTime::currentSecsSinceEpoch());

    jsonObject["Content"] = chatText;//文件名作为文本消息，用户读取到后在通过文件名请求图片资源
    jsonObject["Media"] = 1;//消息类型  1文字 2表情包 3语音 4图片 /表情包
    jsonObject["Type"] = 1;
    // 将 JSON 对象转换为 JSON 文档
    QJsonDocument jsonDoc(jsonObject);
    // 将 JSON 文档转换为字符串发送
    QString jsonString = jsonDoc.toJson(QJsonDocument::Compact);
    emit sendTextMsg(jsonString);//发送文件名的文本消息
}


void ChatDialog::on_switch_key_rabtn_clicked(bool checked)
{
    if( checked == true ){
        _switchkey_dlg = new SwitchKeyDialog(this);
        connect(_switchkey_dlg,&SwitchKeyDialog::openKey_sig,this,&ChatDialog::keyEnterIsTrue);
        connect(_switchkey_dlg,&SwitchKeyDialog::forbidKey_sig,this,&ChatDialog::keyEnterIsFalse);
        QPoint child = ui->switch_key_rabtn->mapToGlobal(QPoint(0,0));//按键全局坐标
        QPoint parent = this->mapToGlobal(QPoint(0,0));//主界面全局坐标
        //_switchkey_dlg界面实际坐标
        int x = child.x() - parent.x() - 155;
        int y = child.y() - parent.y() - 60;
        _switchkey_dlg->setGeometry(x,y,180,65);
        _switchkey_dlg->show();
        return;
    }
    else{
        disconnect(_switchkey_dlg,&SwitchKeyDialog::openKey_sig,this,&ChatDialog::keyEnterIsTrue);
        disconnect(_switchkey_dlg,&SwitchKeyDialog::forbidKey_sig,this,&ChatDialog::keyEnterIsFalse);
        _switchkey_dlg->deleteLater();
        _switchkey_dlg = nullptr;
    }
}


void ChatDialog::on_input_textEdit_textChanged()
{
    QString text = ui->input_textEdit->toPlainText();
    if( text.trimmed().isEmpty() ){
        ui->send_mes_btn->setEnabled(false);
    }
    else{
        ui->send_mes_btn->setEnabled(true);
    }
}

void ChatDialog::init_ui()
{
    ui->send_mes_btn->setEnabled(false);//发送信息按钮初始不可触发

    this->setModal(false);//非模态
    this->setWindowFlags(Qt::WindowCloseButtonHint |
                         Qt::WindowMinMaxButtonsHint);//最大最小化
    QIcon icon(":/images/dog_svg.svg");
    this->setWindowIcon(icon);
    this->setWindowTitle(" ");

    //初始化聊天输入框图标
    QPixmap pixmap(":/images/dog1.png");
    ui->main_lab->setPixmap(pixmap);


    //设置splitter左边界面为最小值，setStretchFactor(0,0)中第一个参数为组件索引，第二个为拉伸比例
    ui->splitter->setStretchFactor(0,0);
    ui->splitter->setStretchFactor(1,1);
    //设置splitter_2，拉伸比例为2比1
    ui->splitter_2->setStretchFactor(0,2);
    ui->splitter_2->setStretchFactor(1,1);

    //隐藏addressBook_list界面，同时只显示一张QListWidget界面
    ui->addressBook_list->setVisible(false);
    //界面右侧首先展示初始界面
    ui->stackedWidget->setCurrentIndex(0);

    //水平滚动将以像素为单位进行
    ui->chat_messages_list->setHorizontalScrollMode(QListWidget::ScrollPerPixel);
    ui->chat_messages_list->verticalScrollBar()->setSingleStep(10);




    //搜索框逻辑
    QPixmap search_pix(":/images/search.png");
    search_pix.scaled(ui->label->size(), Qt::KeepAspectRatio);
    ui->label->setScaledContents(true);
    ui->label->setPixmap(search_pix);
    ui->lineEdit_chat->setPlaceholderText("搜索");
    ui->undo_btn->setVisible(false);//隐藏撤销按钮，当搜索框获取焦点时显示
    //当搜索框获得焦点时候的信号连接
    connect(ui->lineEdit_chat,&SearchLineEdit::hasfocus,this,&ChatDialog::showUndoBtn);
    //当搜索框失去焦点时候的信号连接
    connect(ui->lineEdit_chat,&SearchLineEdit::losefocus,this,&ChatDialog::hideUndoBtn);

    //消息列表逻辑
    ui->chat_list->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);//隐藏垂直滚动条
    ui->chat_list->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);//隐藏水平滚动条
    //将自定义CustomizeWidget中检测鼠标进出事件与滚动滑块显示与隐藏槽绑定
    connect(ui->userData,&CustomizeWidget::enter_signals,this,&ChatDialog::showScrollBar);
    connect(ui->userData,&CustomizeWidget::leave_signals,this,&ChatDialog::hideScrollBar);

    //聊天输入框触发enter快捷键发送消息
    connect(ui->input_textEdit,&ChatInputTextEdit::sendMessage,this,&ChatDialog::on_send_mes_btn_clicked);


}

//void ChatDialog::showChatwidget(QStringList friendInfo)
//{    /*friendInfo储存顺序为<<user_id<<user_msg<<user_name<<user_email<<user_avatar
//    既friendInfo[0]为user_id用户ID*/


//}


void ChatDialog::showContactwidget(QStringList friendInfo)
{
    /*friendInfo储存顺序为<<user_id<<user_msg<<user_name<<user_email<<user_avatar
    既friendInfo[0]为user_id用户ID*/
    ui->user_name_lab->setText(friendInfo[2]);
    //先清除contact_page页面原来的内容
    ui->friend_id->clear();
    ui->friend_name->clear();
    ui->friend_email->clear();
    ui->friend_avatar->clear();

    //在给页面添加好友信息
    ui->friend_id->setText("ID "+friendInfo[0]);
    ui->friend_name->setText(friendInfo[2]);
    ui->friend_email->setText("邮箱 "+friendInfo[3]);
    //在qlabel中显示图片

    //QByteArray image = readBytesFile("resources/usersData/1/avatar/","test.jfif");
    QByteArray image = readBytesFile(AVATAR_PATH,friendInfo[4]);
    loadImage(ui->friend_avatar,image);
    ui->stackedWidget->setCurrentIndex(2);
}

void ChatDialog::loadChatMessageTowidget(QString msgId, double score,QString friend_avatar)
{
    QPixmap pix;
    pix.loadFromData(readBytesFile(AVATAR_PATH,friend_avatar));//好友头像数据
    //加载十条消息，如果少于十条则加载全部
    for(int i=0;i<10;i++){
        //字符串列表储存顺序TargetId, Type, Media, Content
        QStringList msgList = queryMsgByMsgIdAndScore(msgId,score);
        score--;
        if(msgList.isEmpty())
            return;
        //判断消息是用户发送的还是好友或者是时间
        //时间消息
        if(msgList[1].toInt() ==4){
            auto *messageitem = new messageTimeListItem;
            messageitem->setTime(msgList[3]);
            auto *item = new QListWidgetItem;
            item->setSizeHint(QSize(0,60));
            // 插入 item 到列表的顶部（索引为 0）
            ui->chat_messages_list->insertItem(0, item);
            ui->chat_messages_list->setItemWidget(item, messageitem);
        }
        else if(msgList[0].toInt() == user_id){//好友发送的消息
            auto *messageitem = new messageFriendListItem;
            //判断消息是文本还是图片
            //文本
            if(msgList[2].toInt() ==1){
                int height = fontheight(msgList[3]);
                messageitem->SetInfo(msgList[3],pix);
                auto *item = new QListWidgetItem;
                item->setSizeHint(QSize(0,height));
                // 插入 item 到列表的顶部（索引为 0）
                ui->chat_messages_list->insertItem(0, item);
                ui->chat_messages_list->setItemWidget(item, messageitem);

            }
            //图片
            else if(msgList[2].toInt() ==4){
                QPixmap pixMsg;
                pixMsg.loadFromData(readBytesFile(IMAGE_MSG_PATH,msgList[3]));
                messageitem->setInfo(pixMsg,msgList[3],pix);
                auto *item = new QListWidgetItem;
                item->setSizeHint(pixSize(pixMsg));
                // 插入 item 到列表的顶部（索引为 0）
                ui->chat_messages_list->insertItem(0, item);
                ui->chat_messages_list->setItemWidget(item, messageitem);
            }

        }
        else{
            auto *messageitem = new messageUserListItem;
            QPixmap pixmap = ui->avatar->pixmap();//复制左侧用户头像
            //判断消息是文本还是图片
            //文本
            if(msgList[2].toInt() ==1){
                int height = fontheight(msgList[3]);
                messageitem->setInfo(msgList[3],pixmap);
                auto *item = new QListWidgetItem;
                item->setSizeHint(QSize(0,height));
                ui->chat_messages_list->insertItem(0, item);
                ui->chat_messages_list->setItemWidget(item, messageitem);
            }
            //图片
            else if(msgList[2].toInt() ==4){
                QPixmap pixMsg;
                pixMsg.loadFromData(readBytesFile(IMAGE_MSG_PATH,msgList[3]));
                messageitem->setInfo(pixMsg,msgList[3],pixmap);
                auto *item = new QListWidgetItem;
                item->setSizeHint(pixSize(pixMsg));
                // 插入 item 到列表的顶部（索引为 0）
                ui->chat_messages_list->insertItem(0, item);
                ui->chat_messages_list->setItemWidget(item, messageitem);
            }
        }
    }

}

void ChatDialog::init_user(const QJsonArray& jsonfriendlist)
{
    //先获取用户自己的头像图片
    QJsonObject userAvatarJson;
    userAvatarJson["filename"] = user_avatar;
    userAvatarJson["Type"] = 1;//1头像 2聊天消息
    HttpMgr::GetInstance()->GetHttpReq(QUrl(gate_url_prefix+"/toGetImage"),
                                       userAvatarJson, ReqId::ID_LOGIN_GETAVATAR,Modules::thread);


    for (const auto& friendObj : jsonfriendlist) {
        QJsonObject singleFriend = friendObj.toObject();
        QString friend_name = singleFriend["Name"].toString();
        QString friend_email = singleFriend["Email"].toString();
        QString friend_avatar = singleFriend["Avatar"].toString();
        int friend_id = singleFriend["Id"].toInt();

        //获取好友头像图片
        QJsonObject fiendAvatarJson;
        fiendAvatarJson["filename"] = friend_avatar;
        fiendAvatarJson["Type"] = 1;//1头像 2聊天消息
        HttpMgr::GetInstance()->GetHttpReq(QUrl(gate_url_prefix+"/toGetImage"),
                                           fiendAvatarJson, ReqId::ID_LOGIN_GETAVATAR,Modules::thread);


        QString key;//聊天窗口标识,服务器根据key查找聊天信息，两个用户共享一个key
        if(user_id > friend_id) {
            key = "msg_" + QString::number(friend_id) + "_" + QString::number(user_id);
        } else {
            key = "msg_" + QString::number(user_id) + "_" + QString::number(friend_id);
        }

        // 获取单个用户聊天记录
        QJsonObject jsonObject;
        jsonObject["MsgId"] = key;
        HttpMgr::GetInstance()->PostHttpReq(QUrl(gate_url_prefix+"/toGetMsg"),
                                            jsonObject, ReqId::ID_LOGIN_MESSAGES,Modules::thread);

        auto *con_user_wid = new ChatListItem();
        con_user_wid->SetInfo(friend_id,key,friend_name,friend_email,friend_avatar);
        QListWidgetItem *item = new QListWidgetItem;
        item->setSizeHint(QSize(250,70));
        ui->addressBook_list->addItem(item);
        ui->addressBook_list->setItemWidget(item, con_user_wid);

    }

}



void ChatDialog::show_imageInfo()
{
    loadImage(ui->avatar,readBytesFile(AVATAR_PATH,user_avatar));//加载用户头像

    //联系人列表头像加载
    for(int i=0;i<ui->addressBook_list->count();i++){
        QListWidgetItem *item = ui->addressBook_list->item(i);
        ChatListItem *customItem = qobject_cast<ChatListItem*>(ui->addressBook_list->itemWidget(item));
        customItem->setAvatar(customItem->getAvatar());
    }

}


void ChatDialog::on_radioButton_3_clicked()
{
    auto *messageitem = new messageFriendListItem;
    QString icon1(":/images/cat.jpg");
    messageitem->SetInfo("chatText",icon1);
    auto *item = new QListWidgetItem;
    item->setSizeHint(QSize(0,150));
    ui->chat_messages_list->insertItem(6,item);
    ui->chat_messages_list->setItemWidget(item,messageitem);
}

void ChatDialog::slot_chat_mod_finish(ReqId id, QByteArray res, ErrorCodes err)
{
    if(err == ErrorCodes::ERR_NETWORK){
        QMessageBox::critical(this,"错误","请求发送失败！");
        return;
    }
    if(id == ReqId::ID_CHAT_UPREADTIME){
        QMessageBox::question(this,"网络错误",res);
    }


}


//聊天模式按钮
void ChatDialog::on_chat_rabut_clicked(bool checked)
{
    ui->chat_list->setVisible(checked);
    ui->addressBook_list->setVisible(!checked);
}

//联系人模式按钮
void ChatDialog::on_contact_rabut_clicked(bool checked)
{
    ui->chat_list->setVisible(!checked);
    ui->addressBook_list->setVisible(checked);
}

//联系人模式下点击发送消息,创建聊天item在聊天窗口
void ChatDialog::on_contact_send_mes_clicked()
{

    // 获取当前选中 qlistwidgetitem 的索引
    int currentIndex = ui->addressBook_list->currentRow();
    QListWidgetItem *item_cur = ui->addressBook_list->item(currentIndex);
    ChatListItem *customItem = qobject_cast<ChatListItem*>(ui->addressBook_list->itemWidget(item_cur));

    /*friendInfo储存顺序为<<user_id<<user_msg<<user_name<<user_email<<user_avatar
    既friendInfo[0]为user_id用户ID*/
    QStringList friendInfo = customItem->GetInfo();
    //添加item到聊天模式的窗口并且置顶
    auto *con_user_wid = new ChatListItem();
    con_user_wid->SetInfo(friendInfo[0].toInt(),friendInfo[1],friendInfo[2],friendInfo[3],friendInfo[4]);
    double currentTimestamp = QDateTime::currentSecsSinceEpoch();//当前时间戳
    con_user_wid->SetInfo("",0,currentTimestamp,0);
    con_user_wid->setAvatar(friendInfo[4]);//设置头像
    QListWidgetItem *item = new QListWidgetItem;
    item->setSizeHint(QSize(250,70));
    ui->chat_list->insertItem(0,item);
    ui->chat_list->setItemWidget(item, con_user_wid);

    ui->chat_list->setCurrentRow(0);
    ui->chat_rabut->setChecked(true);
    on_chat_rabut_clicked(true);//触发聊天模式按钮

    showChatwidgetInContact(ui->friend_name);

}

void ChatDialog::slot_loadChatItem(QJsonObject lastMsg,QString msgId,int newMesNums)
{
    QString messageStr = lastMsg["message"].toString();
    double score = lastMsg["score"].toDouble();
    // 解析 message 字段中的 JSON 字符串
    QJsonDocument messageDoc = QJsonDocument::fromJson(messageStr.toUtf8());
    QJsonObject messageObj = messageDoc.object();

    //获取聊天窗口好友id
    int targetId = messageObj["TargetId"].toInt();
    int id;
    if(targetId == user_id)
        id = getAnotherUserId(msgId,targetId);
    else
        id = targetId;
    QString mes = messageObj["Content"].toString();//消息
    double time = messageObj["CreateTime"].toDouble();
    qDebug() <<time<<"time";
    //strl[0]为id，后续依次为name,email,avatar
    QStringList strl = getContactDataById(id);//获取好友基本信息
    if(strl.isEmpty())
        return;
    auto chatItem = new ChatListItem;
    chatItem->SetInfo(id,msgId,strl[1],strl[2],strl[3]);
    chatItem->SetInfo(mes,newMesNums,time,score);
    chatItem->setAvatar(strl[3]);//设置头像

    QListWidgetItem *item = new QListWidgetItem;
    item->setSizeHint(QSize(250,70));
    ui->chat_list->insertItem(0,item);
    ui->chat_list->setItemWidget(item, chatItem);
}

void ChatDialog::slot_recvMsg(QString msg)
{
    // 将 JSON 字符串转换为 QJsonDocument 对象
    QJsonDocument jsonDoc = QJsonDocument::fromJson(msg.toUtf8());
    // 检查 JSON 文档是否有效
    if (jsonDoc.isNull()) {
        qDebug() << "Invalid JSON document";
        return ;
    }
    QJsonObject mesObj = jsonDoc.object();
    QString contentMsg = mesObj["Content"].toString();
    int sendUserId = mesObj["UserId"].toInt();
    int type = mesObj["Type"].toInt();
    int media = mesObj["Media"].toInt();
    double createTime = mesObj["CreateTime"].toDouble();
//    double readTime = mesObj["ReadTime"].toDouble();
    double readTime = 0;
    double score = 0;
    //获取聊天标识符
    QString msgId;
    if(user_id > sendUserId) {
        msgId = "msg_" + QString::number(sendUserId) + "_" + QString::number(user_id);
    } else {
        msgId = "msg_" + QString::number(user_id) + "_" + QString::number(sendUserId);
    }

    //获取聊天窗口最新消息score，如果该聊天信息不在聊天列表，则新建一个在聊天窗口在聊天列表
    for(int i=0;i<ui->chat_list->count();i++){
        QListWidgetItem *item = ui->chat_list->item(i);
        ChatListItem *customItem = qobject_cast<ChatListItem*>(ui->chat_list->itemWidget(item));
        if(customItem->getMsgId() == msgId){
            score = customItem->getScore();
            score += 1;
            //判断该消息是否是时间，如果是，则储存到本地数据库后直接return
            if(type == 4){
                saveMessageToDatabase(MAIN,msgId,sendUserId,type,media,contentMsg,createTime,readTime,score);
                return;
            }
            //判断score+1的分数在数据库有没有，有则代表上一个消息是时间，此消息score应该为时间消息的score+1
            QStringList msgInfo = queryMsgByMsgIdAndScore(msgId,score);
            if(!msgInfo.isEmpty()){
                score += 1;
            }
            customItem->SetInfo(contentMsg,1,QDateTime::currentSecsSinceEpoch(),score);
            break;
        }
    }
    //如果score为0，证明聊天列表没有该msgId聊天窗口，新建一个
    if(score ==0){
        score = 1;
        //判断该消息是否是时间，如果是，则储存到本地数据库后直接return
        if(type == 4){
            saveMessageToDatabase(MAIN,msgId,sendUserId,type,media,contentMsg,createTime,readTime,score);
            return;
        }
        //判断score的分数在数据库有没有，有则代表上一个消息是时间，此消息score应该为时间消息的score+1
        QStringList msgInfo = queryMsgByMsgIdAndScore(msgId,score);
        if(!msgInfo.isEmpty()){
            score += 1;
        }
        QStringList friendInfo = getContactDataById(sendUserId);//顺序friend_id, name, email, avatar
        if(friendInfo.isEmpty()){
            qDebug()<< msg<<123;
        }
        auto chatlistItem = new ChatListItem;
        chatlistItem->SetInfo(sendUserId,msgId,friendInfo[1],
                              friendInfo[2],friendInfo[3]);
        double currentTimestamp = QDateTime::currentSecsSinceEpoch();//当前客户端时间戳
        chatlistItem->SetInfo(contentMsg,1,currentTimestamp,score);
        chatlistItem->setAvatar(friendInfo[3]);
        QListWidgetItem *item = new QListWidgetItem;
        item->setSizeHint(QSize(250,70));
        ui->chat_list->insertItem(0,item);
        ui->chat_list->setItemWidget(item, chatlistItem);
    }

    saveMessageToDatabase(MAIN,msgId,sendUserId,type,media,contentMsg,createTime,readTime,score);


}

void ChatDialog::showChatwidgetInContact(QLabel *lab)
{
    if(ui->chat_messages_list->count()>0)
        ui->chat_messages_list->clear();
    //先清空默认文本或者缓存文本
    ui->user_name_lab->text().clear();
    ui->user_name_lab->setText(lab->text());

    ui->stackedWidget->setCurrentIndex(1);
}

void ChatDialog::on_chat_list_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous)
{
    // 判断 current 和 previous 是否相同
    if (current == previous) {
        return; // 如果相同则直接返回，不做后续处理
    }

    //先清空界面原来的内容
    if(ui->chat_messages_list->count()>0)
        ui->chat_messages_list->clear();
    //先清空默认文本或者缓存文本
    ui->user_name_lab->text().clear();

    ChatListItem *customItem = qobject_cast<ChatListItem*>(ui->chat_list->itemWidget(current));
    /*friendInfo储存顺序为<<user_id<<user_msg<<user_name<<user_email<<user_avatar
    既friendInfo[0]为user_id用户ID*/
    QStringList friendInfo = customItem->GetInfo();
    ui->user_name_lab->setText(friendInfo[2]);
    double score = customItem->getScore();
    int newMsgNums = customItem->getNewMsgNums();

    loadChatMessageTowidget(friendInfo[1],score,friendInfo[4]);//加载10条消息在聊天消息展示窗口
    bool ok = updateReadTime(friendInfo[1],score,newMsgNums);
    if(!ok){
        qDebug()<< "数据库更新消息读取时间错误：on_chat_list_itemPressed,updateReadTime";
    }
    customItem->reSetNewMsgNums();//将新消息数置0
    //界面右侧显示加载界面
    ui->stackedWidget->setCurrentIndex(1);
}


void ChatDialog::on_addressBook_list_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous)
{
    // 判断 current 和 previous 是否相同
    if (current == previous) {
        return; // 如果相同则直接返回，不做后续处理
    }
    ChatListItem *customItem = qobject_cast<ChatListItem*>(ui->addressBook_list->itemWidget(current));
    showContactwidget(customItem->GetInfo());
}

